package com.aitou.mrylive.presentation.ui.main.webview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.aitou.mrylive.R;
import com.aitou.mrylive.data.repository.SourceFactory;
import com.aitou.mrylive.presentation.ui.base.BaseActivity;
import com.aitou.mrylive.presentation.ui.main.MainActivity;
import com.aitou.mrylive.util.L;
import com.umeng.analytics.MobclickAgent;

/**
 * @author Muyangmin
 * @since 1.0.0
 * 我的等级
 */
public class SimpleWebViewActivity extends BaseActivity {

    private static final String EXTRA_URL = "url";

    private String mUrl;

    private TextView tvTitle;
    private WebView mWebView;
    private final static int FILECHOOSER_RESULTCODE = 1;
    private ValueCallback<Uri[]> mUploadMessage;

    public static Intent createIntent(Context context, String url) {
        Intent intent = new Intent(context, SimpleWebViewActivity.class);
        intent.putExtra(EXTRA_URL, url);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_simple_webview;
    }

    @Override
    protected void parseIntentData(Intent intent, boolean isFromNewIntent) {
        super.parseIntentData(intent, isFromNewIntent);
        mUrl = intent.getStringExtra(EXTRA_URL);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void findViews(Bundle savedInstanceState) {
        mWebView = $(R.id.simple_webview);

        WebSettings settings = mWebView.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);

        tvTitle = $(R.id.tv_toolbar_title);
        if (TextUtils.isEmpty(mUrl)) {
            toastShort("请求地址有误");
            finish();
        } else {
            mWebView.setWebChromeClient(new SimpleWebChromeClient());
            mWebView.setWebViewClient(new SimpleWebViewClient());
            mWebView.getSettings().setJavaScriptEnabled(true);
            String absPath = SourceFactory.wrapPath(mUrl);
            L.d(LOG_TAG, "Loading page %s", absPath);
            mWebView.loadUrl(absPath);
        }

        mWebView.setWebChromeClient(new TestWebChromeClient(new WebChromeClient()){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (tvTitle != null && !(TextUtils.isEmpty(title))) {
                    tvTitle.setText(title);
                }
            }

            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType)
            {
                openFileChooser(uploadFile);
            }

            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType,
                                        String capture)
            {
                openFileChooser(uploadFile);
            }
            public  boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams){
                mUploadMessage = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                SimpleWebViewActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), SimpleWebViewActivity.FILECHOOSER_RESULTCODE);
                return true;
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri[] a=new Uri[1];
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            Log.i("mrl",result+" ");
            a[0]=result;
            if (result!=null) {
                mUploadMessage.onReceiveValue(a);
            }
            mUploadMessage = null;
        }
    }

    @Override
    protected void init() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            try {
                mWebView.stopLoading();
                mWebView.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        MobclickAgent.onPageStart("我的等级");
        super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPageEnd("我的等级");
        super.onPause();
    }

    private class SimpleWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("mrl",url+"   "+mUrl+"这个是网址");
            if (Uri.parse(url).getHost().equals(mUrl)) {
                // This is my web site, so do not override; let my WebView load the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
//            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//            startActivity(intent);
            return false;
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
        }

    }

    private class SimpleWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (tvTitle != null && !(TextUtils.isEmpty(title))) {
                tvTitle.setText(title);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    abstract class TestWebChromeClient extends WebChromeClient
    {

        private WebChromeClient mWrappedClient;

        protected TestWebChromeClient(WebChromeClient wrappedClient)
        {
            mWrappedClient = wrappedClient;
        }

        /** {@inheritDoc} */
        @Override
        public void onProgressChanged(WebView view, int newProgress)
        {
            mWrappedClient.onProgressChanged(view, newProgress);
        }

        /** {@inheritDoc} */
        @Override
        public void onReceivedTitle(WebView view, String title)
        {
            mWrappedClient.onReceivedTitle(view, title);
        }

        /** {@inheritDoc} */
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon)
        {
            mWrappedClient.onReceivedIcon(view, icon);
        }

        /** {@inheritDoc} */
        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed)
        {
            mWrappedClient.onReceivedTouchIconUrl(view, url, precomposed);
        }

        /** {@inheritDoc} */
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback)
        {
            mWrappedClient.onShowCustomView(view, callback);
        }

        /** {@inheritDoc} */
        @Override
        public void onHideCustomView()
        {
            mWrappedClient.onHideCustomView();
        }

        /** {@inheritDoc} */
        @Override
        public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture,
                                      Message resultMsg)
        {
            return mWrappedClient.onCreateWindow(view, dialog, userGesture, resultMsg);
        }

        /** {@inheritDoc} */
        @Override
        public void onRequestFocus(WebView view)
        {
            mWrappedClient.onRequestFocus(view);
        }

        /** {@inheritDoc} */
        @Override
        public void onCloseWindow(WebView window)
        {
            mWrappedClient.onCloseWindow(window);
        }

        /** {@inheritDoc} */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result)
        {
            return mWrappedClient.onJsAlert(view, url, message, result);
        }

        /** {@inheritDoc} */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result)
        {
            return mWrappedClient.onJsConfirm(view, url, message, result);
        }

        /** {@inheritDoc} */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result)
        {
            return mWrappedClient.onJsPrompt(view, url, message, defaultValue, result);
        }

        /** {@inheritDoc} */
        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message,
                                        JsResult result)
        {
            return mWrappedClient.onJsBeforeUnload(view, url, message, result);
        }

        /** {@inheritDoc} */
        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier,
                                            long currentQuota, long estimatedSize, long totalUsedQuota,
                                            WebStorage.QuotaUpdater quotaUpdater)
        {
            mWrappedClient.onExceededDatabaseQuota(url, databaseIdentifier, currentQuota,
                    estimatedSize, totalUsedQuota, quotaUpdater);
        }

        /** {@inheritDoc} */
        @Override
        public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
                                             WebStorage.QuotaUpdater quotaUpdater)
        {
            mWrappedClient
                    .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota, quotaUpdater);
        }

        /** {@inheritDoc} */
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback)
        {
            mWrappedClient.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        /** {@inheritDoc} */
        @Override
        public void onGeolocationPermissionsHidePrompt()
        {
            mWrappedClient.onGeolocationPermissionsHidePrompt();
        }

        /** {@inheritDoc} */
        @Override
        public boolean onJsTimeout()
        {
            return mWrappedClient.onJsTimeout();
        }

        /** {@inheritDoc} */
        @Override
        @Deprecated
        public void onConsoleMessage(String message, int lineNumber, String sourceID)
        {
            mWrappedClient.onConsoleMessage(message, lineNumber, sourceID);
        }

        /** {@inheritDoc} */
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage)
        {
            return mWrappedClient.onConsoleMessage(consoleMessage);
        }

        /** {@inheritDoc} */
        @Override
        public Bitmap getDefaultVideoPoster()
        {
            return mWrappedClient.getDefaultVideoPoster();
        }

        /** {@inheritDoc} */
        @Override
        public View getVideoLoadingProgressView()
        {
            return mWrappedClient.getVideoLoadingProgressView();
        }

        /** {@inheritDoc} */
        @Override
        public void getVisitedHistory(ValueCallback<String[]> callback)
        {
            mWrappedClient.getVisitedHistory(callback);
        }

        /** {@inheritDoc} */

        public void openFileChooser(ValueCallback<Uri> uploadFile)
        {
            ((TestWebChromeClient) mWrappedClient).openFileChooser(uploadFile);
        }

        /** {@inheritDoc} */

        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType)
        {
            ((TestWebChromeClient) mWrappedClient).openFileChooser(uploadFile, acceptType);
        }

        /** {@inheritDoc} */

        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType,
                                    String capture)
        {
            ((TestWebChromeClient) mWrappedClient).openFileChooser(uploadFile, acceptType,
                    capture);
        }
    }
}
